package org.jeecg.modules.stoneentry.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.manage.entity.CustomerInfo;
import org.jeecg.modules.manage.service.ICustomerInfoService;
import org.jeecg.modules.stoneentry.entity.StoneEntry;
import org.jeecg.modules.stoneentry.service.IStoneEntryService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description:  石出入库
 * @Author: jerryzhu
 * @Date:   2021-11-15
 * @Version: V1.0
 */
@Api(tags=" 石出入库")
@RestController
@RequestMapping("/stoneEntry")
@Slf4j
public class StoneEntryController extends JeecgController<StoneEntry, IStoneEntryService> {
	
	@Autowired
	private IStoneEntryService stoneEntryService;
	
	@Autowired
	private ISysUserService sysUserService;
	
	@Autowired
	private ICustomerInfoService customerInfoService;
	
	
	
	/**
	 * 石出入库明细分页列表
	 *
	 * @param stoneEntry
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = " 石出入库-石出入库明细分页")
	@ApiOperation(value=" 石出入库-石出入库明细分页列表", notes=" 石出入库-石出入库明细分页列表")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(StoneEntry stoneEntry,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<StoneEntry> queryWrapper = QueryGenerator.initQueryWrapper(stoneEntry, req.getParameterMap());
		Page<StoneEntry> page = new Page<StoneEntry>(pageNo, pageSize);
		IPage<StoneEntry> pageList = stoneEntryService.selectStoneEntryPage(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 * 仓库库存数据列表
	 *
	 * @param stoneEntry
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "石出入库-仓库库存数据列表")
	@ApiOperation(value = "石出入库-仓库库存数据列表", notes = "石出入库-仓库库存数据列表")
	@GetMapping(value = "/queryStorageData")
	public Result<?> queryStorageData(@RequestParam(name = "storageId",required = true) String storageId)  {
		List<StoneEntry> list = stoneEntryService.getStoneEntryStorageSummaryList(storageId);
		return Result.OK(list);
	}
	
	/**
	 * 员工库存数据列表
	 *
	 * @param stoneEntry
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "石出入库-员工库存数据列表")
	@ApiOperation(value = "石出入库-员工库存数据列表", notes = "石出入库-员工库存数据列表")
	@GetMapping(value = "/queryPersonData")
	public Result<?> queryPersonData(@RequestParam(name = "userId",required = true) String userId)  {
		List<StoneEntry> list = stoneEntryService.getStoneEntryPersonSummaryList(userId);
		return Result.OK(list);
	}
	
	
	/**
	 *   批量添加
	 *
	 * @param stoneEntry
	 * @return
	 */
	@AutoLog(value = "石出入库-批量添加")
	@ApiOperation(value = "石出入库-批量添加", notes = "石出入库-批量添加")
	@PostMapping(value = "/batchAdd")
	@Transactional
	public Result<?> batchAdd(@RequestBody JSONObject jsonObject) {
		String sendPerson = jsonObject.getString("sendPerson");//发出员工
		String sendStorage = jsonObject.getString("sendStorage");//发出仓库
		String sendCustomer = jsonObject.getString("sendCustomer");//发出客户
		String receivePerson = jsonObject.getString("receivePerson");//接收员工
		String receiveStorage = jsonObject.getString("receiveStorage");//接收仓库
		String receiveCustomer = jsonObject.getString("receiveCustomer");//接收客户
		Integer type = jsonObject.getInteger("type");//出入库类型
		String jsonString = JSONArray.toJSONString(jsonObject.get("data"));
		JSONArray jsonArray = JSONArray.parseArray(jsonString);
		Date now = new Date();//当前时间
		if(jsonArray != null && jsonArray.size() > 0) {
			for(int i = 0; i < jsonArray.size(); i++) {
				String str = JSONArray.toJSONString(jsonArray.get(i));
				JSONObject obj = JSONObject.parseObject(str);
				String id = obj.getString("id");//主键ID
				if(id != null && !"".equals(id)) {
					StoneEntry stoneEntry = new StoneEntry();
					stoneEntry.setStoneActionType(type);//操作类型
					stoneEntry.setSn("SON-"+System.currentTimeMillis());//操作流水号
					stoneEntry.setSendPerson(sendPerson);//发出员工
					stoneEntry.setSendStorage(sendStorage);//发出仓库
					stoneEntry.setSendCustomer(sendCustomer);//发出客户
					stoneEntry.setSendTime(now);//发出时间
					stoneEntry.setReceivePerson(receivePerson);//接收员工
					stoneEntry.setReceiveStorage(receiveStorage);//接收仓库
					stoneEntry.setReceiveCustomer(receiveCustomer);//接收客户
					stoneEntry.setReceiveTime(now);//接收时间
					stoneEntry.setWorkNum(obj.getString("workNum"));//工单号
					stoneEntry.setPn(obj.getString("pn"));//拆分页
					stoneEntry.setStoneName(obj.getString("stoneName"));//石名称
					stoneEntry.setPurchaseOrderNum(obj.getString("purchaseOrderNum"));//采购单号
					String codeNum = obj.getString("codeNum");
					codeNum = (codeNum == null || "".equals(codeNum)) ? String.valueOf(FillRuleUtil.executeRule("stone_card_code",null)) : codeNum;
					stoneEntry.setCodeNum(codeNum);//石卡号
					stoneEntry.setStoneNum(obj.getString("stoneNum"));//石号
					stoneEntry.setCateId(obj.getString("cateId"));//石类
					stoneEntry.setSizeNum(obj.getString("sizeNum"));//筛号
					stoneEntry.setLevel(obj.getString("level"));//级别
					stoneEntry.setShape(obj.getString("shape"));//形状
					stoneEntry.setStyle(obj.getString("style"));//规格
					stoneEntry.setNeatness(obj.getString("neatness"));//净度
					stoneEntry.setCutting(obj.getString("cutting"));//车工
					stoneEntry.setColor(obj.getString("color"));//颜色
					stoneEntry.setTexture(obj.getString("texture"));//质地
					stoneEntry.setAngle(obj.getString("angle"));//角度
					stoneEntry.setWeight(obj.getBigDecimal("weight"));//单粒重
					stoneEntry.setGoodStoneCount(obj.getInteger("goodStoneCount"));//好石数
					stoneEntry.setGoodStoneWeight(obj.getBigDecimal("goodStoneWeight"));//好石重
					stoneEntry.setBadStoneCount(obj.getInteger("badStoneCount"));//坏石数
					stoneEntry.setBadStoneWeight(obj.getBigDecimal("badStoneWeight"));//坏石重
					stoneEntry.setInlay(obj.getString("inlay"));//镶法
					stoneEntry.setStoneUnitCost(obj.getBigDecimal("stoneUnitCost"));//成本单价
					stoneEntry.setStoneUnitPrice(obj.getBigDecimal("stoneUnitPrice"));//单价
					stoneEntry.setBatchNum(obj.getString("batchNum"));//批号
					stoneEntry.setReceiveOrderNum(obj.getString("receiveOrderNum"));//来单号
					stoneEntry.setMainStone(obj.getString("mainStone"));//主副石
					stoneEntry.setInvoiceType(obj.getString("invoiceType"));//发票类型
					stoneEntry.setCurrencyType(obj.getString("currencyType"));//实际币种
					stoneEntry.setStoneUnitPlay(obj.getBigDecimal("stoneUnitPlay"));//实际单价
					stoneEntry.setStoneCost(obj.getBigDecimal("stoneCost"));//实际金额
					stoneEntry.setExchangeRate(obj.getString("exchangeRate"));//汇率
					stoneEntry.setCountPricePattern(obj.getString("countPricePattern"));//计价方式
					stoneEntry.setRemark(obj.getString("remark"));//备注
					stoneEntryService.save(stoneEntry);
				}
			}
			return Result.ok("操作成功！");
		} else {
			return Result.error("操作失败，请勾选要保存的数据！");
		}
	}
	
	/**
	 *  编辑
	 *
	 * @param stoneEntry
	 * @return
	 */
	@AutoLog(value = "石出入库-编辑")
	@ApiOperation(value = "石出入库-编辑", notes = "石出入库-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody StoneEntry stoneEntry) {
		stoneEntryService.updateById(stoneEntry);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "石出入库-通过id删除")
	@ApiOperation(value = "石出入库-通过id删除", notes = "石出入库-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name = "id",required = true) String id) {
		stoneEntryService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "石出入库-批量删除")
	@ApiOperation(value = "石出入库-批量删除", notes = "石出入库-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required = true) String ids) {
		this.stoneEntryService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "石出入库-通过id查询")
	@ApiOperation(value = "石出入库-通过id查询", notes = "石出入库-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required = true) String id) {
		StoneEntry stoneEntry = stoneEntryService.getById(id);
		if(stoneEntry==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(stoneEntry);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param stoneEntry
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StoneEntry stoneEntry) {
        return super.exportXls(request, stoneEntry, StoneEntry.class, " 石出入库");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, StoneEntry.class);
    }

	
	
	/**
	 *  获取发出/接收员工的姓名
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "石出入库-获取接收员工的姓名")
	@ApiOperation(value = "石出入库-获取接收员工的姓名", notes = "石出入库-获取接收员工的姓名")
	@GetMapping(value = "/getPerson")
	public Result<?> getPerson(@RequestParam(name = "username",required = true) String username) {
		SysUser sysUser = sysUserService.getUserByName(username);
		return Result.OK(sysUser.getRealname()+"("+sysUser.getWorkNo()+")");
	}
	
	/**
	 *  获取发出/接收客户的姓名
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "石出入库-获取接收客户的姓名")
	@ApiOperation(value = "石出入库-获取接收客户的姓名", notes = "石出入库-获取接收客户的姓名")
	@GetMapping(value = "/getCustomer")
	public Result<?> getCustomer(@RequestParam(name = "id",required = true) String id) {
		CustomerInfo customerInfo = customerInfoService.getById(id);
		return Result.OK(customerInfo.getCusName());
	}
	
	/**
	 *  获取发出/接收仓库的姓名
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "石出入库-获取接收仓库的姓名")
	@ApiOperation(value = "石出入库-获取接收仓库的姓名", notes = "石出入库-获取接收仓库的姓名")
	@GetMapping(value = "/getStorage")
	public Result<?> getStorage(@RequestParam(name = "id",required = true) String id) {
		String sendStorage = stoneEntryService.getStorageName(id);
		return Result.OK(sendStorage);
	}
	
	/**
	 * 通过石卡号codeNum查询石卡信息
	 *
	 * @param codeNum
	 * @return
	 */
	@AutoLog(value = "石卡信息-通过石卡号查询")
	@ApiOperation(value = "石卡信息-通过石卡号查询", notes = "石卡信息-通过石卡号查询")
	@GetMapping(value = "/queryStoneCardInfoByCodeNum")
	public Result<?> queryStoneCardInfoByCodeNum(@RequestParam(name = "codeNum",required = true) String codeNum) {
		Map<String,String> map = stoneEntryService.queryStoneCardInfoByCodeNum(codeNum);
		if(map == null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(map);
	}
	
	/**
	 * 通过石号stoneNum查询石号信息
	 *
	 * @param stoneNum
	 * @return
	 */
	@AutoLog(value = "石号信息-通过石号查询")
	@ApiOperation(value = "石号信息-通过石号查询", notes = "石号信息-通过石号查询")
	@GetMapping(value = "/queryStoneStyleByStoneNum")
	public Result<?> queryStoneStyleByStoneNum(@RequestParam(name = "stoneNum",required = true) String stoneNum) {
		Map<String,String> map = stoneEntryService.queryStoneStyleByStoneNum(stoneNum);
		if(map == null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(map);
	}
}
